package com.cuit.qx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cuit.qx.aop.OperLog;
import com.cuit.qx.bean.Threshold;
import com.cuit.qx.bean.User;
import com.cuit.qx.service.ThresholdManagementService;
import com.cuit.qx.utils.ReturnData;
import com.cuit.qx.utils.ReturnStateCode;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static org.thymeleaf.util.ListUtils.isEmpty;

/**
 * @Author:wjd
 * @Description: 阈值管理
 * @date:Created in 16:04 2020/9/16
 * @Modified By:
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/system")
public class ThresholdValueController {

    @Autowired
    ThresholdManagementService service;


    /**
     * @return
     * @Author:wjd on 2020/9/16 14:48
     * @param: pageNo页数   pageSize 每页的条数
     * @Description: 查询所有日志
     */
    @RequestMapping("/getAllThreshold")
    @ResponseBody
    @OperLog(operModul = "阈值管理", operType = "1", operDesc = "查询阈值信息")
    public ReturnData getAllLog(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

        List<Threshold> allThresholdData = service.getAllThresholdData(pageNo, pageSize);

        if (!isEmpty(allThresholdData)) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(), allThresholdData);
        } else {
            return new ReturnData(ReturnStateCode.SUCCEEBUT.getCode(), ReturnStateCode.SUCCEEBUT.getMsg());
        }
    }

    @RequestMapping("/addThreshold")
    @ResponseBody
    @OperLog(operModul = "阈值管理", operType = "2", operDesc = "增加阈值信息")
    public ReturnData addThreshold(@RequestBody Threshold threshold) {
//        Threshold threshold = JSON.parseObject(jsonObject.toJSONString(), Threshold.class);
        int state = service.insertThreshold(threshold);
        if (state > 0) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(), threshold);
        } else {
            return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.SUCCEEBUT.getMsg());
        }
    }


    /**
     * @return
     * @Author:wjd on 2020/9/16 18:16
     * @param:
     * @Description: 导入阈值表
     */
    @RequestMapping(value = "/importExcel")
    @OperLog(operModul = "阈值管理", operType = "5", operDesc = "导入阈值管理数据")
    public ReturnData importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                int count = 0;
                List<Threshold> listSysAnnouncements = ExcelImportUtil.importExcel(file.getInputStream(), Threshold.class, params);
                List<Threshold> collect = listSysAnnouncements.stream().filter(item -> judgeNumber(item.getHumidity()) &&
                        judgeNumber(item.getTemperature()) &&
                        judgeNumber(item.getPressure()) &&
                        judgeNumber(item.getWind()) &&
                        judgeNumber(item.getHumidity()) &&
                        judgeNumber(item.getPrecipitation())

                ).collect(Collectors.toList());
                for (Threshold sysAnnouncementExcel : collect) {
                    if (sysAnnouncementExcel.getStation() != null) {
                        QueryWrapper<Threshold> queryWrapper=new QueryWrapper();
                        queryWrapper.eq("station",sysAnnouncementExcel.getStation());
                        Threshold one = service.getOne(queryWrapper);
                        if (one==null){
                            service.save(sysAnnouncementExcel);
                        }else {
                            count++;
                        }
                    } else {
                        count++;
                    }
                }
//                return new ReturnData(ReturnStateCode.SUCCEE.getCode(), "文件导入成功！数据行数：" + listSysAnnouncements.size());
                if (count == 0) {
                    return new ReturnData(ReturnStateCode.SUCCEE.getCode(), "文件导入成功！导入数据行数：" + collect.size()+"不符合条件数据"+(listSysAnnouncements.size()-collect.size()+"行"));
                } else {
                    return new ReturnData(ReturnStateCode.SUCCEE.getCode(), "文件处理成功！成功导入数据行数：" + (collect.size() - count)  +"！不符合条件行数："+(listSysAnnouncements.size()-collect.size()+count));
                }
            } catch (Exception e) {
//                log.error(e.getMessage(),e);
                return new ReturnData(ReturnStateCode.FAILED.getCode(), "文件导入失败:原因" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return new ReturnData(ReturnStateCode.FAILED.getCode(), "文件导入失败！");
    }

    /**
     * @return
     * @Author:wjd on 2020/9/16 17:45
     * @param:
     * @Description: 阈值模板下载
     */
    @RequestMapping(value = "/exportXlsTemplate")
    @OperLog(operModul = "阈值管理", operType = "6", operDesc = "阈值管理模板下载")
    public ModelAndView exportXlsTemplate(HttpServletResponse res, HttpServletRequest req) throws IOException {
        User user = (User) req.getSession().getAttribute("user");
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<Threshold> sysUsers = new ArrayList<Threshold>();
        Threshold c = new Threshold();
        //如果需要在阈值表内加案例内容 则加上该代码    c.setStation("52314");
        sysUsers.add(c);
        // 导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, new String("阈值管理模板".getBytes(),"UTF-8"));
        mv.addObject(NormalExcelConstants.CLASS, Threshold.class);
        ExportParams exportParams = new ExportParams("导入阈值管理", "导出人:" + user.getUsername(), "阈值管理");
        exportParams.setImageBasePath("");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, sysUsers);
        return mv;
    }

    /**
     * 根据id单条修改阈值信息
     *
     * @param threshold 阈值对象
     * @return
     */
    @RequestMapping(value = "/updateThreshold", method = RequestMethod.POST)
    @OperLog(operModul = "阈值管理", operType = "3", operDesc = "根据id单条修改阈值信息")
    @ResponseBody
    public ReturnData updateThreshold(@RequestBody Threshold threshold) {
        int num = service.updateThresholdId(threshold);
        if (num > 0) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(),num);
        } else {
            return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg(),num);
        }
    }

    /**
     * 根据id批量修改阈值信息
     *
     * @param thresholds 多个阈值对象
     * @return
     */
    @RequestMapping(value = "/updateThresholdList", method = RequestMethod.POST)
    @OperLog(operModul = "阈值管理", operType = "3", operDesc = "根据id批量修改阈值信息")
    @ResponseBody
    public ReturnData updateThresholdList(@RequestBody List<Threshold> thresholds) {
        int num = service.updateThresholdList(thresholds);
        if (num > 0) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(),num);
        } else {
            return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg(),num);
        }
    }

    @RequestMapping(value = "/updateBatchByElement",method = RequestMethod.POST)
    @OperLog(operModul = "阈值管理", operType = "3", operDesc = "批量修改阈值信息")
    public ReturnData BatchUpdateByElement(@RequestBody Map<String,Object> map){
        String ids = (String) map.get("ids");
        String wind = (String) map.get("wind");
        String tem = (String) map.get("tem");
        String rain = (String) map.get("rain");
        String press = (String) map.get("press");
        String hum = (String) map.get("hum");
        Boolean aBoolean = service.updateBatchByElement(ids, wind, tem, rain, press, hum);
        if (aBoolean){
          return  new ReturnData(ReturnStateCode.SUCCEE.getCode(),ReturnStateCode.SUCCEE.getMsg());
        }
        return new  ReturnData(ReturnStateCode.FAILED.getCode(),ReturnStateCode.FAILED.getMsg());
    }

    /**
     * 根据条件查询阈值信息
     *
     * @param pageNo      页数
     * @param pageSize    每页条数
     * @param station     站点
     * @param stationName 站点名
     * @return
     */
    @RequestMapping(value = "/getThreshold", method = RequestMethod.GET)
    @OperLog(operModul = "阈值管理", operType = "1", operDesc = "根据条件查询阈值信息")
    @ResponseBody
    public ReturnData getThreshold(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   String station, String stationName) {
        List<Threshold> thresholdData = service.getThreshold(pageNo, pageSize, station, stationName);
        int count = service.getCount(station, stationName);
        if (!isEmpty(thresholdData)) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(), count, thresholdData);
        } else {
            return new ReturnData(ReturnStateCode.SUCCEEBUT.getCode(), ReturnStateCode.SUCCEEBUT.getMsg(), count, thresholdData);
        }
    }

    /**
     * 根据阈值id删除站点信息
     *
     * @param id 阈值id
     * @return
     */
    @RequestMapping(value = "/deleteThresholdById", method = RequestMethod.GET)
    @OperLog(operModul = "阈值管理", operType = "4", operDesc = "根据阈值id删除站点信息")
    @ResponseBody
    public ReturnData deleteThresholdById(String id) {
        int num = service.deleteThresholdById(id);
        if (num > 0) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(),num);
        } else {
            return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg(),num);
        }
    }

    /**
     * 根据阈值id批量删除站点信息
     *
     * @param ids 多个阈值id
     * @return
     */
    @RequestMapping(value = "/deleteThresholdByIds", method = RequestMethod.GET)
    @OperLog(operModul = "阈值管理", operType = "4", operDesc = "根据阈值id批量删除站点信息")
    @ResponseBody
    public ReturnData deleteThresholdByIds(String ids) {
        int num = service.deleteThresholdByIds(ids);
        if (num > 0) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(),num);
        } else {
            return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg(),num);
        }
    }

    public static boolean judgeNumber(String number){
        return Pattern.compile("([1-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9])").matcher(number).matches();
    }
}
